<!--
 * @Author: zqx me_zqx@163.com
 * @Date: 2025-02-25 17:12:26
 * @LastEditors: zqx me_zqx@163.com
 * @LastEditTime: 2025-09-01 18:19:29
 * @FilePath: /XMate-h5/src/views/myXmate/myTeam/teamReport/teamReportDetail.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="flex flex-col h-screen bg-[#F5F5F5]">
    <!-- 固定头部 -->
    <div class="sticky top-0 z-10 bg-white">
      <div class="flex justify-between items-center px-4 py-4">
        <!-- 切换标签 -->
        <div class="flex items-center p-0.5">
          <div
            class="h-8 px-6 min-w-[88px] text-center leading-8 text-sm rounded-full cursor-pointer transition-all duration-300 whitespace-nowrap"
            :class="activeTab === 'team'
              ? 'text-[#2B65F4] bg-[#E6EEFF]'
              : 'text-[#666] bg-[#F4F5F6]'
              " @click="scrollToSection('team')">
            团队情况
          </div>
          <div
            class="h-8 px-6 min-w-[88px] text-center leading-8 text-sm rounded-full cursor-pointer transition-all duration-300 whitespace-nowrap ml-2"
            :class="activeTab === 'customer'
              ? 'text-[#2B65F4] bg-[#E6EEFF]'
              : 'text-[#666] bg-[#F4F5F6]'
              " @click="scrollToSection('customer')">
            客户情况
          </div>
        </div>

        <!-- 替换原有的下拉菜单为 chooseTeamView -->
        <div class="flex items-center" @click="showTeamPicker">
          <span class="text-sm text-[#333]">{{ currentDprt.name || "选择团队" }}</span>
          <van-icon name="arrow-down" class="ml-1" />
        </div>
      </div>
    </div>

    <!-- 滚动区域 -->
    <div class="flex-1 overflow-y-auto" ref="scrollContainer" @scroll="handleScroll">
      <!-- 团队情况区域 -->
      <div ref="teamSection" class="flex flex-col gap-4 p-4">
        <scoreCardItem title="沟通计划" type="visitPlan" tooltip-content="沟通计划完成率：基于沟通计划录制的沟通记录数 / 沟通计划总数" :isTeam="isTeam"
          :memberData="memberBoardList" :teamData="teamBoardList" :items="visitPlanOverview" />

        <scoreCardItem title="沟通记录" type="visitRecord"
          tooltip-content="沟通总次数：仅统计有效沟通次数，沟通记录处理状态为【处理失败、文件处理中、会话字幕量不足】标识为无效数据" :isTeam="isTeam"
          :memberData="memberBoardList" :teamData="teamBoardList" :items="visitRecordOverview" />
        <!-- <scoreCardItem title="目标达成" tooltip-content="记录相关说明" :isTeam="isTeam" :memberData="memberBoardList"
          :teamData="teamBoardList" :items="[
            {
              title: '沟通目标达成率',
              content: formatValue(
                (teamOverview.visitTargetAchievementRate || 0) * 100,
                2,
                true
              ),
              unit: '%',
              props: 'visitTargetAchievementRate',
              growth: calculateGrowthRate('visitTargetAchievementRate'),
            },
          ]" /> -->

        <scoreCardItem title="沟通表现" tooltip-content="记录相关说明" :isTeam="isTeam" :memberData="memberBoardList"
          :teamData="teamBoardList" :items="[
            {
              title: '能力评估达标率',
              content: formatValue((teamOverview.salesAbilityPassRate || 0) * 100, 2, true),
              unit: '%',
              props: 'salesAbilityPassRate',
              growth: calculateGrowthRate('salesAbilityPassRate'),
            },
            {
              title: '任务完成达标率',
              content: formatValue(
                (teamOverview.taskCompletePassRate || 0) * 100,
                2,
                true
              ),
              unit: '%',
              props: 'taskCompletePassRate',
              growth: calculateGrowthRate('taskCompletePassRate'),
            },
          ]" />
      </div>

      <!-- 客户情况区域 -->
      <div ref="customerSection">
        <reportCustomerList :startTime="parameter.st" :endTime="parameter.et" />
      </div>
    </div>

    <!-- 添加 chooseTeamView 组件 -->
    <chooseTeamView ref="chooseTeamViewRef" :defaultTeam="currentDprt" @onConfirm="handleTeamConfirm" />
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, computed } from "vue";
import scoreCardItem from "@/views/myXmate/components/scoreCardItem.vue";
import { useMyXmateStore, useCommonStore } from "@/store";
import { useRoute } from "vue-router";
import reportCustomerList from "./reportCustomerList.vue";
import chooseTeamView from "@/views/myXmate/components/chooseTeamView.vue";
import { teamReportUserListAPI, teamReportTeamListAPI } from "@/services/myXmate";
import { formatValue } from "@/utils/num";

const myXmateStore = useMyXmateStore();
const commonStore = useCommonStore();
const route = useRoute();
// 团队看板总览
// const teamOverview = computed(() => myXmateStore.teamOverview);

const enableBusinessOpportunity = computed(() => commonStore.enableBusinessOpportunity);
console.log("enableBusinessOpportunity: ", enableBusinessOpportunity.value);

// 当前激活的标签
const activeTab = ref("team");

const isTeam = computed(() => {
  return currentDprt.value.children?.length > 0;
});

// 筛选数据
const filterData = reactive({
  timeRange: 0,
  memberType: 0,
});

const chooseTeamViewRef = ref(null);

const parameter = reactive({
  type: route.query.type,
  reportTime: route.query.reportTime,
  st: route.query.st,
  et: route.query.et,
});

onMounted(async () => {
  await getDprtInfo();
  getData();
});

const mydprt = computed(() => myXmateStore.selfDprt);
const currentDprt = ref({});
const teammId = computed(() => currentDprt.value.id);
const teamReportLatest2 = computed(() => myXmateStore.teamReportLatest2);
const teamOverview = computed(() => {
  if (!teamReportLatest2.value) return {};
  return teamReportLatest2.value[teamReportLatest2.value.length - 1] || {};
});

const visitPlanOverview = computed(() => {
  let arr = [
    {
      title: '沟通计划总数',
      content: teamOverview.value.totalVisitPlanCount,
      props: 'totalVisitPlanCount',
      growth: calculateGrowthRate('totalVisitPlanCount'),
    },
    // {
    //   title: '沟通计划完成率',
    //   content: formatValue(teamOverview.value.visitPlanCompletionRate || 0, 2, true),
    //   props: 'visitPlanCompletionRate',
    //   unit: '%',
    //   growth: calculateGrowthRate('visitPlanCompletionRate'),
    // },
    {
      title: '沟通计划覆盖客户数',
      content: teamOverview.value.visitPlanCustomerCount,
      props: 'visitPlanCustomerCount',
      growth: calculateGrowthRate('visitPlanCustomerCount'),
    },
    {
      title: '沟通计划覆盖商机数',
      content: teamOverview.value.visitPlanOpportunityCount,
      props: 'visitPlanOpportunityCount',
      growth: calculateGrowthRate('visitPlanOpportunityCount'),
    },
    {
      title: '人均沟通计划数',
      content: formatValue(teamOverview.value.averageVisitPlanPerPerson || 0, 2),
      props: 'averageVisitPlanPerPerson',
      growth: calculateGrowthRate('averageVisitPlanPerPerson'),
      fixedNum: 2,
    },
  ]
  !enableBusinessOpportunity.value && arr.splice(3, 1);
  return arr;
});

const visitRecordOverview = computed(() => {
  let arr = [
    {
      title: '沟通总次数',
      content: teamOverview.value.totalVisitCount,
      props: 'totalVisitCount',
      growth: calculateGrowthRate('totalVisitCount'),
    },
    {
      title: '沟通覆盖客户数',
      content: teamOverview.value.visitedCustomerCount,
      props: 'visitedCustomerCount',
      growth: calculateGrowthRate('visitedCustomerCount'),
    },
    {
      title: '沟通覆盖商机数',
      content: teamOverview.value.visitedOpportunityCount,
      props: 'visitedOpportunityCount',
      growth: calculateGrowthRate('visitedOpportunityCount'),
    },
    {
      title: '人均沟通次数',
      content: formatValue(teamOverview.value.averageVisitsPerPerson || 0, 2),
      props: 'averageVisitsPerPerson',
      growth: calculateGrowthRate('averageVisitsPerPerson'),
      fixedNum: 2,
    },
  ]
  !enableBusinessOpportunity.value && arr.splice(2, 1);
  return arr;
})

async function getDprtInfo() {
  if (!mydprt.value) {
    await myXmateStore.getMydprtAction();
  }
  const rootDprtChildren = mydprt.value?.children || [];
  if (rootDprtChildren.length > 0) {
    currentDprt.value = rootDprtChildren[0];
  }
}

const customerListParam = computed(() => {
  return {
    pageNumber: 1,
    pageSize: 200,
    dptIds: [teammId.value],
    startTime: parameter.st + " 00:00:00",
    endTime: parameter.et + " 23:59:59",
  };
});

function getCustomerList() {
  myXmateStore.getTeamReportCustomerListAction(customerListParam.value);
}

function getTeamReportLatest2() {
  myXmateStore.getTeamReportLatest2Action(
    teammId.value,
    parameter.type,
    parameter.reportTime
  );
}

// 人员列表
const memberBoardList = ref([]);
// 团队列表
const teamBoardList = ref([]);
async function getData() {
  getCustomerList();
  getTeamReportLatest2();

  // teamId, periodType, reportTime
  const data = {
    teamId: teammId.value,
    periodType: parameter.type,
    reportTime: parameter.reportTime,
  };
  if (isTeam.value) {
    let res = await teamReportTeamListAPI(data);
    teamBoardList.value = res?.datas || [];
    console.log("teamBoardList: ", teamBoardList.value);
  } else {
    let res = await teamReportUserListAPI(data);
    memberBoardList.value = res?.datas || [];
    console.log("memberBoardList: ", memberBoardList.value);
  }
}

// 显示团队选择器
const showTeamPicker = () => {
  chooseTeamViewRef.value.show();
};

// 处理团队选择确认
const handleTeamConfirm = (teams) => {
  console.log("handleTeamConfirm: ", teams);
  chooseTeamViewRef.value.hide();
  currentDprt.value = teams[0];
  // 重新获取数据
  getData();
};

// 监听筛选条件变化
watch(
  [() => filterData.timeRange, () => filterData.memberType],
  ([newTimeRange, newMemberType]) => {
    // TODO: 调用接口获取数据
    console.log("筛选条件变化：", {
      timeRange: newTimeRange,
      memberType: newMemberType,
    });
    fetchReportData();
  }
);

// 获取报告数据
const fetchReportData = async () => {
  try {
    // TODO: 实现API调用
    // const response = await getTeamReport({
    //   timeRange: filterData.timeRange,
    //   memberType: filterData.memberType
    // })
    // reportData.value = response.data
  } catch (error) {
    console.error("获取团队报告失败：", error);
  }
};

// 新增的响应式引用
const scrollContainer = ref(null);
const teamSection = ref(null);
const customerSection = ref(null);

// 滚动到指定区域
const scrollToSection = (section) => {
  activeTab.value = section;
  const target = section === "team" ? teamSection.value : customerSection.value;
  target.scrollIntoView({ behavior: "smooth" });
};

// 处理滚动事件
const handleScroll = () => {
  if (!scrollContainer.value || !teamSection.value || !customerSection.value) return;

  const container = scrollContainer.value;
  const customerRect = customerSection.value.getBoundingClientRect();
  const containerTop = container.getBoundingClientRect().top;

  // 当客户区域的顶部进入视图的一半时切换 tab
  if (customerRect.top - containerTop < container.clientHeight / 2) {
    activeTab.value = "customer";
  } else {
    activeTab.value = "team";
  }
};

// 计算增长率
const calculateGrowthRate = (key) => {
  if (!teamReportLatest2.value || teamReportLatest2.value.length !== 2) {
    return "error";
  }

  const currentValue = teamReportLatest2.value[1][key];
  const previousValue = teamReportLatest2.value[0][key];

  if (previousValue === 0 || previousValue === undefined || previousValue === null) {
    return "error";
  }

  return Number((((currentValue - previousValue) / previousValue) * 100).toFixed(2));
};
</script>

<style lang="less" scoped>
.team-report-detail {
  padding: 20px;
}

.visit-details {
  margin-top: 20px;
}

.sticky {
  position: sticky;
  top: 0;
  background: white;
  z-index: 10;
}
</style>
